﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Xinkui.Common.Enum;
using CommonFramework.Attach;
using Xinkui.Common.FileAction;
using CommonFramework.Utility.ImageThumbnail;
using CommonFramework.Utility;
using System.IO;

namespace Xinkui.Common {
    public class FileUpload : FileBase {
        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="postFile">上传空间</param>
        /// <param name="sType">上传类型</param>
        /// <param name="sID">类型对应ID</param>
        /// <param name="userID">上传用户，可为0</param>
        /// <returns></returns>
        public static FileEntity Upload(HttpPostedFile postFile, ESourceType sType, int sID, int userID) {
            FileSettingEntity fileVaild = FileManger.GetFileSetting((int)sType);

            if (fileVaild == null) {
                throw new Exception("为配置文件");
            }
            //验证文件
            CheckPostedFile(postFile, fileVaild);

            FileEntity fEntity = getFileByPostFile(postFile, sType, sID, userID);

            //原图单独保存
            postFile.SaveAs(fEntity.ServerPath);

            if (fileVaild.FileType == "Image") {
                //生成缩略图
                SaveThumbnail(fileVaild, fEntity);
            }

            FileDataAccess.CreateFile(fEntity);

            return fEntity;
        }

        /// <summary>
        /// 更新附件表内容
        /// </summary>
        /// <param name="attachID">附件ID</param>
        /// <param name="sType">附件类型</param>
        /// <param name="sID">附件对应类型ID</param>
        /// <returns></returns>
        public static string UpdateAttachment(int attachID, ESourceType sType, int sID) {
            FileSettingEntity fileVaild = FileManger.GetFileSetting((int)sType);
            if (fileVaild == null) {
                throw new Exception("为配置文件");
            }

            FileEntity fEntity = FileDataAccess.GetFileEntityByID(attachID);

            if (fEntity != null) {
                fEntity.SourceID = sID;
                fEntity.SourceType = sType;
                FileDataAccess.UpdateAttachment(fEntity);
                return fEntity.FileID + fEntity.FileExtension.ToLower();
            }
            else {
                return string.Empty;
            }

        }

        /// <summary>
        /// 保存附件并生成缩略图,删除以前数据
        /// </summary>
        /// <param name="attachID">附件ID</param>
        /// <param name="sType">附件类型</param>
        /// <param name="sID">附件对应类型ID</param>
        /// <param name="isDelete">是否删除以前</param>
        /// <returns></returns>
        public static string SaveAttachment(int attachID, ESourceType sType, int sID) {
            return SaveAttachment(attachID, sType, sID, true);
        }

        /// <summary>
        /// 保存附件并生成缩略图
        /// </summary>
        /// <param name="attachID">附件ID</param>
        /// <param name="sType">附件类型</param>
        /// <param name="sID">附件对应类型ID</param>
        /// <param name="isDelete">是否删除以前</param>
        /// <returns></returns>
        public static string SaveAttachment(int attachID, ESourceType sType, int sID, bool isDelete) {

            FileSettingEntity fileVaild = FileManger.GetFileSetting((int)sType);
            if (fileVaild == null) {
                throw new Exception("为配置文件");
            }

            FileEntity fEntity = FileDataAccess.GetFileEntityByID(attachID);

            if (fEntity != null) {
                if (isDelete) {
                    FileDataAccess.DeleteFileByType(attachID, sID, (int)sType);
                }

                fEntity.SourceID = sID;
                fEntity.SourceType = sType;
                //移动图片，生成新位置
                fEntity.ServerPath = MoveFile(fEntity);
                FileDataAccess.UpdateAttachment(fEntity);
            }

            SaveThumbnail(fileVaild, fEntity);
            return fEntity.FileID + fEntity.FileExtension.ToLower();
        }

        /// <summary>
        /// 移动图片
        /// </summary>
        /// <param name="fEntity"></param>
        /// <returns></returns>
        private static string MoveFile(FileEntity fEntity) {
            string newPath = GetDirectoryPath(fEntity.FileID, fEntity.SourceType, fEntity.FileExtension.ToLower());

            File.Move(fEntity.ServerPath, newPath);
            return newPath;

        }

        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="fileVaild">配置类型</param>
        /// <param name="fEntity">文件实体</param>
        private static void SaveThumbnail(FileSettingEntity fileVaild, FileEntity fEntity) {
            if (!string.IsNullOrEmpty(fileVaild.FileSize) && fileVaild.FileType == "Image" && fEntity != null) {
                string[] sizeList = fileVaild.FileSize.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);

                List<ThumbnailEntity> thumbnailList = new List<ThumbnailEntity>();
                foreach (string size in sizeList) {
                    string[] dimension = size.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);
                    int width = ConvertHelper.ToType<int>(dimension[0], 0);
                    int height = ConvertHelper.ToType<int>(dimension[1], 1);

                    thumbnailList.Add(new ThumbnailEntity {
                        Width = width,
                        Height = height,
                        ThumbnailPath = fEntity.ServerPath.Replace(fEntity.FileExtension.ToLower(), size.Replace("-", "_") + fEntity.FileExtension.ToLower())
                    });
                }
                if (thumbnailList.Count > 0) {
                    ImageThumbnailHelper.Thumbnail(fEntity.ServerPath, thumbnailList);
                }
            }
        }

        /// <summary>
        /// 验证文件有效性
        /// </summary>
        /// <param name="postFile"></param>
        /// <param name="sType"></param>
        public static void CheckPostedFile(HttpPostedFile postFile, FileSettingEntity fileVaild) {
            bool falg = false;
            if (fileVaild.Length < postFile.ContentLength)//验证文件长度
            {
                falg = true;
            }
            if (!fileVaild.ContentType.ToLower().Contains(postFile.ContentType.ToLower()))//验证文件类型
            {
                falg = true;
            }
            if (!fileVaild.Extension.ToLower().Contains(Path.GetExtension(postFile.FileName.ToLower())))//验证文件扩展名
            {
                falg = true;
            }

            if (falg) {
                throw new Exception(fileVaild.ErrorKey);
            }
        }

        /// <summary>
        /// 初始化上传对象
        /// </summary>
        /// <param name="postFile"></param>
        /// <param name="sType"></param>
        /// <param name="sID"></param>
        /// <param name="userID"></param>
        /// <returns></returns>
        private static FileEntity getFileByPostFile(HttpPostedFile postFile, ESourceType sType, int sID, int userID) {
            FileEntity fEntity = new FileEntity();
            fEntity.FileID = FileDataAccess.GetNewFileID();
            fEntity.FileExtension = Path.GetExtension(postFile.FileName);
            fEntity.FileName = Path.GetFileName(postFile.FileName);
            fEntity.FileSize = postFile.ContentLength;
            fEntity.SourceID = sID;
            fEntity.SourceType = sType;
            fEntity.UpdateDate = DateTime.Now;
            fEntity.UserID = userID;
            fEntity.ServerPath = GetDirectoryPath(fEntity.FileID, fEntity.SourceType, fEntity.FileExtension.ToLower());
            fEntity.FilePath = Path.GetFileName(fEntity.ServerPath);

            return fEntity;
        }

    }
}
